//
//  ZYUserCore.swift
//  SwiftDemo1
//
//  Created by wangzhipan on 2025/6/17.
//

import Foundation

class ZYUserCore {
    static let shareCore = ZYUserCore()
    var account: ZYUserAccount? {
        didSet {
            guard let tmpAccount = account else {
                return
            }
            do {
                let data = try NSKeyedArchiver.archivedData(withRootObject: tmpAccount, requiringSecureCoding: false)
                try data.write(to: NSURL(fileURLWithPath: accountPath) as URL)
                Logger.info("archived UserAccount success")
            } catch {
                Logger.info("archived UserAccount error")
            }
        }
    }
    
    var accountPath: String {
        if let documentPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first {
            return (documentPath as NSString).appendingPathComponent("account.plist")
        }
        return ""
    }
    
    var isLogin: Bool {
        guard let account = self.account else {
            return false
        }
        
        let expiresDate = account.expires_date
        
        return expiresDate.compare(Date()) == .orderedDescending
    }
    
    private init() {
        readAccount()
    }
    
    private func readAccount() {
        Logger.info(accountPath)
        guard let data = NSData(contentsOfFile: accountPath) as? Data else {
            return
        }
        do {
            let account = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data) as? ZYUserAccount
//            let account = try NSKeyedUnarchiver.unarchivedObject(ofClass: ZYUserAccount.self, from: data)
            self.account = account
            Logger.info("unarchivedObject userAccount success")
        } catch (let error) {
            Logger.info("unarchivedObject userAccount error: \(error.localizedDescription)")
        }
    }
}
